package com.yang.Hash_;

import java.util.HashMap;

public class two_sum {
    public static void main(String[] args) {
        SolutionTwoSum solutionTwoSum = new SolutionTwoSum();
        int[] temp = {5,5,3};
        int target = 10;
        int[] ints = solutionTwoSum.twoSum(temp, target);
        for (int i = 0; i < ints.length; i++) {
            System.out.println(ints[i]);
        }
    }
}

// 两数之和 关键在于使用HashMap 如果不满足那就存到HashMap中 下次遇到重复的也就不会再存他了
// 让目标数依次 - 数组里的数 得到的数就在HashMap中查找是否存在，存在则满足
class SolutionTwoSum {
    public int[] twoSum(int[] nums, int target) {
        int [] result = new int[2];
        if(nums == null){
            return result;
        }
        HashMap<Integer, Integer> integers = new HashMap<>();
        for (int i = 0; i <nums.length ; i++) {
            if( integers.containsKey(target - nums[i] )) {
                result[0] = integers.get(target - nums[i]);
                result[1] = i;
            }
            integers.put(nums[i], i);
        }
        return result;
    }
}
